package com.hudongwx.godoffood.activity.Community_Activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.LoginActivity;
import com.hudongwx.godoffood.fragment.communityFragment.viewPager.ImageActivity;
import com.hudongwx.godoffood.resfRecycle.MyRecyclerView;
import com.hudongwx.godoffood.utils.API.API;
import com.hudongwx.godoffood.utils.MyApplication;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 帖子详情
 */
@ContentView(R.layout.activity_details)
public class DetailsActivity extends AppCompatActivity {
    @ViewInject(R.id.details_gridview)
    private GridView gridView;
    @ViewInject(R.id.details_tv1)
    private TextView tv1;
    @ViewInject(R.id.details_tv2)
    private TextView tv2;
    @ViewInject(R.id.details_tv3)
    private TextView tv3;
    @ViewInject(R.id.details_tv4)
    private TextView tv4;
    @ViewInject(R.id.details_iv)
    private ImageView iv;
    @ViewInject(R.id.details_edit)
    private EditText et;
    @ViewInject(R.id.details_textview)
    private TextView textView;
    @ViewInject(R.id.details_recycleview)
    private RecyclerView recycleview;
    private String TAG = "DetailsActivity";
    @ViewInject(R.id.details_no_content)
    private RelativeLayout no_content;
    private String postid;
    private String parnetname = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        init();
    }
    //初始化
    private void init() {
        Intent intent = getIntent();
        postid = intent.getStringExtra("postid");
        loadJson(postid);
        loadHuitie();

    }

    //弹举报的窗口
    @Event(R.id.details_tv5)
    private void popuWindows(View view) {
        Intent intent = new Intent(DetailsActivity.this, ReportActivity.class);
        startActivity(intent);
    }

    @Event(R.id.ll_back)
    private void back(View view) {
        finish();
    }

    private void loadJson(String url) {
        RequestParams requestParams = new RequestParams(API.getDetailsUrl(url));
        x.http().get(requestParams, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONObject jsonData = result.getJSONObject("Data");
                    tv1.setText(jsonData.getString("UserName"));
                    tv2.setText(jsonData.getString("DateTime"));
                    tv3.setText(jsonData.getString("Title"));
                    String content = jsonData.getString("Content");
                    if (!"".equals(content)) {
                        tv4.setVisibility(View.VISIBLE);
                        tv4.setText(jsonData.getString("Content"));
                    }
                    String imageurl = jsonData.getString("UserIcon");
                    et.setHint("评论" + jsonData.getString("UserName"));
                    int count = jsonData.getInt("CommentCount");
                    if (count==0){
                        no_content.setVisibility(View.VISIBLE);
                    }else {
                        no_content.setVisibility(View.GONE);
                    }

                    textView.setText("全部回帖" + "(" + count + ")");
                    x.image().bind(iv, imageurl);
                    ItemAdapter itemadapter = new ItemAdapter(jsonData.getJSONArray("ListFile"));
                    gridView.setAdapter(itemadapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //加载回帖的数据
    private void loadHuitie() {
        String huitie = "http://api.shiandianping.com/api/sourceAndroidDianPing/v3.1.0/Comment?pageSize=10&postId=" + postid + "&pageIndex=1";
        final RequestParams requestParams = new RequestParams(huitie);
        x.http().get(requestParams, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                List<JSONObject> jsonObjectss = parser2ListItem(result);
                MyhuitieAdapter myhuitieadapter = new MyhuitieAdapter(jsonObjectss);
                LinearLayoutManager llm = new LinearLayoutManager(DetailsActivity.this);
                recycleview.setLayoutManager(llm);
                recycleview.setAdapter(myhuitieadapter);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }


    /**
     * 这是小图片的适配器
     */
    class ItemAdapter extends BaseAdapter {
        private JSONArray data;
        //创建一个集合装载图片
        private ArrayList<String> list = new ArrayList<>();
        public ItemAdapter(JSONArray data) {
            this.data = data;
            addlist();
        }

        //将图片的地址添加进集合
        public void addlist() {
            for (int i = 0; i < data.length(); i++) {
                try {
                    list.add(data.getJSONObject(i).getString("Url"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public int getCount() {
            return data.length();

        }

        @Override
        public Object getItem(int position) {
            try {
                return data.getJSONObject(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageItemHolder imageItemHolder = null;
            gridViewClickListener gridViewclickListener = new gridViewClickListener();
            if (convertView == null) {
                imageItemHolder = new ImageItemHolder();
                convertView = getLayoutInflater().inflate(R.layout.gridview_showdan_image, null);
                imageItemHolder.iv1 = (ImageView) convertView.findViewById(R.id.showdan_image3);
                convertView.setTag(imageItemHolder);
            } else {
                imageItemHolder = (ImageItemHolder) convertView.getTag();
            }
            try {
                String imageUrl = data.getJSONObject(position).getString("Url");
                x.image().bind(imageItemHolder.iv1, imageUrl);
                Map<String, Object> map = new HashMap<>();
                map.put("list", list);
                map.put("position", position);
                imageItemHolder.iv1.setTag(map);
                imageItemHolder.iv1.setOnClickListener(gridViewclickListener);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }

    class ImageItemHolder {
        private ImageView iv1;
    }

    //适配器
    class MyhuitieAdapter extends RecyclerView.Adapter<MyhuitieHolder> {
        private List<JSONObject> data;

        public MyhuitieAdapter(List<JSONObject> list) {
            this.data = list;
        }

        @Override
        public MyhuitieHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //设置parent 后才能让recyclerview的宽度才会不出错
            View view = getLayoutInflater().inflate(R.layout.activity_details_item, parent, false);
            return new MyhuitieHolder(view);
        }

        @Override
        public void onBindViewHolder(MyhuitieHolder holder, int position) {
            try {
                JSONObject item = data.get(position);
                x.image().bind(holder.iv, item.getString("UserIcon"));
                holder.tv1.setText(item.getString("UserName"));
                holder.tv2.setText(item.getString("DateTime"));
                holder.tv3.setText(item.getString("Content"));
                int floor = item.getInt("Floor");
                holder.tv5.setText(floor + "F");
                JSONArray sonComment = item.getJSONArray("SonComment");
                MyHuifuAdapter myhuifuadapter = new MyHuifuAdapter(sonComment);
                LinearLayoutManager llm = new LinearLayoutManager(DetailsActivity.this);
                holder.myrecycleview.setLayoutManager(llm);
                holder.myrecycleview.setAdapter(myhuifuadapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }

    /**
     * 这是评论item的装载器
     */
    class MyhuitieHolder extends RecyclerView.ViewHolder {
        private ImageView iv;
        private TextView tv1, tv2, tv3, tv5;
        private RecyclerView myrecycleview;

        public MyhuitieHolder(View itemView) {
            super(itemView);
            iv = (ImageView) itemView.findViewById(R.id.details_item_iv);
            tv1 = (TextView) itemView.findViewById(R.id.details_item_tv1);
            tv2 = (TextView) itemView.findViewById(R.id.details_item_tv2);
            tv3 = (TextView) itemView.findViewById(R.id.details_item_tv3);
            tv5 = (TextView) itemView.findViewById(R.id.details_item_tv5);
            myrecycleview = (RecyclerView) itemView.findViewById(R.id.details_myrecycleview);
        }
    }

    /**
     * 把获取到的json数据，解析添加到一个List里面
     *
     * @param data
     * @return
     */
    private List<JSONObject> parser2ListItem(JSONObject data) {
        List<JSONObject> list = new ArrayList<>();
        try {
            JSONArray jsonArray = data.getJSONArray("Data");
            int len = jsonArray.length();
            for (int i = 0; i < len; i++) {
                list.add(jsonArray.getJSONObject(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    //回复的适配器
    class MyHuifuAdapter extends RecyclerView.Adapter<MyHuifuHolder> {
        private JSONArray data;

        public MyHuifuAdapter(JSONArray data) {
            this.data = data;
        }

        @Override
        public MyHuifuHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //设置parent 后才能让recyclerview的宽度才会不出错
            View view = getLayoutInflater().inflate(R.layout.huifu_item_layout, parent, false);
            return new MyHuifuHolder(view);
        }

        @Override
        public void onBindViewHolder(MyHuifuHolder holder, int position) {
            try {
                JSONObject item = (JSONObject) data.get(position);
                parnetname = item.getString("ParnetName");
                boolean isOp = item.getBoolean("IsOP");

                if (parnetname.equals("null")) {
                    if (isOp) holder.image.setVisibility(View.VISIBLE);
                    holder.tv1.setText(item.getString("UserName"));
                    holder.tv2.setText(":" + item.getString("Content"));
                } else {
                    holder.tv1.setText(item.getString("UserName"));
                    holder.tv2.setText(" 回复 ");
                    holder.tv3.setText(item.getString("ParnetName"));
                    holder.tv4.setText(":" + item.getString("Content"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public int getItemCount() {
            return data.length();
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }
    }

    //下面回复的装载器
    class MyHuifuHolder extends RecyclerView.ViewHolder {
        private TextView tv1, tv2, tv3, tv4;
        private ImageView image;

        public MyHuifuHolder(View itemView) {
            super(itemView);
            tv1 = (TextView) itemView.findViewById(R.id.huifu_tv1);
            tv2 = (TextView) itemView.findViewById(R.id.huifu_tv2);
            tv3 = (TextView) itemView.findViewById(R.id.huifu_tv3);
            tv4 = (TextView) itemView.findViewById(R.id.huifu_tv4);
            image = (ImageView) itemView.findViewById(R.id.huifu_iv);
        }
    }

    //gridview 的点击事件
    class gridViewClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Map<String, Object> map = (Map<String, Object>) v.getTag();
            ArrayList<String> list = (ArrayList<String>) map.get("list");
            int position = (int) map.get("position");
            Intent intent = new Intent(DetailsActivity.this, ImageActivity.class);
            intent.putExtra("position", position);
            intent.putStringArrayListExtra("list", list);
            startActivity(intent);
        }
    }

    @Event(R.id.details_send)
    private void send(View view){
        if (MyApplication.getStorage("Uid").equals("1")){
            Toast.makeText(DetailsActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
        }else {
            startActivity(new Intent(DetailsActivity.this, LoginActivity.class));
        }
    }

}
